﻿
//文档就绪函数
$(function () {
    show();
});
//仓库类型下拉框
layui.use('form', function () {
    var form = layui.form;
    $.ajax({
        url: "/Warehouse/GetWarehouseTypeShow",
        type: "get",
        data: { token: localStorage.getItem("token") },
        success: function (data) {
            var obj = JSON.parse(data);
            console.log(obj.data)
            var options = '<option value="">请选择</option>'; // 添加默认选项
            $.each(obj.data, function (index, item) {
                options += '<option value="' + item.warehouseTypeId + '">' + item.warehouseTypeName + '</option>';
            });
            $("#warehouseTypeId").html(options);
            form.render('select'); // 重新渲染下拉框
        },
        error: function () {
            console.log("获取数据失败");
            // 可以考虑显示一个错误消息给用户
        }
    });
});
var totalCount = 0;
var pageIndex = 1;
var pageSize = 100;
//仓库显示
function show() {
    layui.use('table', function () {
        var table = layui.table;
        //查询
        var warehouseNo = $("#warehouseNo").val();
        var warehouseName = $("#warehouseName").val();
        var departmentId = $("#departmentId").val();
        var warehouseTypeId = $("#warehouseTypeId").val();
        $.ajax({
            url: "/Warehouse/GetWarehouseShow",
            //url: 'http://10.223.8.18:8000/warehouseRead/api/WarehouseMange/GetWarehouse',
            type: "get",
            data: {
                warehouseNo: warehouseNo,
                warehouseName: warehouseName,
                departmentId: departmentId || 0,
                warehouseTypeId: warehouseTypeId || 0,
                pageIndex: pageIndex,
                pageSize: pageSize,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                var obj = JSON.parse(res);
                console.log(obj)
                if (obj.code === 0) {
                    totalCount = obj.data.totalCount
                    console.log(obj.data.list)
                    var inst = table.render({
                        elem: '#warehouseData',//对应HTML中表格的id
                        data: obj.data.list,//绑定获取的数据
                        toolbar: '#toolbarDemo',//导出
                        defaultToolbar: ['exports'],//导出
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'warehouseNo', title: '仓库编号', width: 140 },
                            { field: 'warehouseName', title: '仓库名称', width: 110 },
                            {
                                field: 'leaseDate', title: '租赁时间', templet: function (d) {
                                    return formatTime(d.leaseDate);
                                }, width: 170
                            },
                            { field: 'warehouseTypeName', title: '仓库类型', width: 120 },
                            { field: 'departmentId', title: '所属部门', width: 100 },
                            {
                                field: 'whetherDisable', title: '是否禁用', width: 100, templet: function (d) {
                                    if (d.whetherDisable === false) {
                                        return '<span>否</span>';
                                    } else {
                                        return '<span>是</span>';
                                    }
                                }
                            },
                            // { field: 'sex', title: '性别', width: 80, edit: 'text', sort: true },
                            {
                                field: 'whetherDefault', title: '是否默认', width: 100, templet: function (d) {
                                    if (d.whetherDefault === false) {
                                        return '<span>否</span>';
                                    } else {
                                        return '<span>是</span>';
                                    }
                                }
                            },
                            { field: 'warehouseAddress', title: '地址', width: 110 },
                            { field: 'warehouseArea', title: '面积', width: 80 },
                            { field: 'warehouseContact', title: '联系人', width: 110 },
                            { field: 'warehousePhone', title: '电话', width: 130 },
                            {
                                field: '', title: '操作', templet: function (d) {
                                    return '<a class="layui-btn layui-btn-edit layui-btn-xs" lay-on="test-page-edit" onclick="updateData(' + d.warehouseId + ')"><i class="layui-icon layui-icon-edit"></i>编辑</a> ' +
                                        '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteData(' + d.warehouseId + ')"><i class="layui-icon layui-icon-delete"></i>删除</a>';
                                }
                            }
                        ]],
                        page: true, // 是否显示分页
                        count: totalCount,
                        limits: [5, 8, 10],
                        limit: 5,// 每页默认显示的数量
                        curr: pageIndex,
                    })
                } else {
                    console.log(res.msg);
                }
            },
            error: function () {
                console.log("获取数据失败");
                // 可以考虑显示一个错误消息给用户
            }
        });

    });
}

//仓库删除
window.deleteData = function (warehouseId) {
    layer.confirm('确定要删除该条数据吗？', function (index) {
        //var warehouseId = {
        //    warehouseId: warehouseId
        //}
        console.log(warehouseId)
        $.ajax({
            type: "post",
            url: "/Warehouse/GetDelectWarehouse",  // 替换为实际的后台删除数据接口地址
            // contentType: 'application/json',
            data: {
                warehouseId: warehouseId,
                token: localStorage.getItem("token"),
            },
            // data: { data: JSON.stringify({ warehouseId: warehouseId }) },
            success: function (res) {
                var obj = JSON.parse(res)
                if (obj.code === 1) {
                    layer.alert("删除成功");
                    show();  // 重新加载数据，刷新表格显示
                    console.log(obj.code)
                } else {
                    layer.alert("删除失败");
                }
            },
            error: function () {
                layer.msg('删除失败，请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }
        });
        layer.close(index);
    });
};

// 点击编辑按钮的事件处理
$('#batchUpdBtn').click(function () {
    var table = layui.table;
    // 获取选中行的数据（这里主要是获取warehouseId）
    var checkStatus = table.checkStatus('warehouseData');
    var selectedData = checkStatus.data.map(function (item) {
        return item.warehouseId;
    });
    console.log(selectedData);
    if (selectedData.length === 0) {
        layer.msg("请选择一条要编辑的数据", { icon: 2 });
        return;
    }
    localStorage['warehouseId'] = selectedData;
    location.href = '/Warehouse/WarehouseUpd';
});
//仓库编辑
window.updateData = function (warehouseId) {
    localStorage['warehouseId'] = warehouseId;
    location.href = '/Warehouse/WarehouseUpd';
}
//批量删除
$('#batchDeleteButton').click(function () {
    var table = layui.table;
    // 获取选中行的数据（这里主要是获取warehouseId）
    var checkStatus = table.checkStatus('warehouseData');
    var selectedData = checkStatus.data.map(function (item) {
        return item.warehouseId;
    });

    if (selectedData.length === 0) {
        layer.msg("请至少选择一条要删除的数据", { icon: 2 });
        return;
    }

    console.log(selectedData);
    layer.confirm('确定要批量删除选中的' + selectedData.length + '条数据吗？', function (index) {
        var warehouseId = {
            warehouseId: selectedData
        }
        // 发送批量删除请求到后端
        $.ajax({
            url: "/Warehouse/GetPlDelectWarehouse", // 后端处理批量删除的接口地址，需根据实际情况调整
            type: "post",
            // contentType: "application/json",
            data: {
                warehouseId: warehouseId,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                var res = JSON.parse(res)
                console.log(res.code);
                if (res.code > 0) {
                    layer.msg("批量删除成功", { icon: 1 })
                    // 重新加载表格数据，展示更新后的列表
                    show();
                } else {
                    layer.msg("批量删除失败:" + res.message, { icon: 2 });
                }
            },
            error: function () {
                console.log("批量删除数据失败");
                // 可以考虑显示一个错误消息给用户
            }
        });
    })
})
//时间格式
function formatTime(timeStamp) {
    if (timeStamp) {
        var date = new Date(timeStamp);
        var year = date.getFullYear(); // 获取年份
        var month = ('0' + (date.getMonth() + 1)).slice(-2); // 获取月份，+1是因为getMonth()返回的月份是从0开始计数的
        var day = ('0' + date.getDate()).slice(-2); // 获取日期
        var hour = ('0' + date.getHours()).slice(-2); // 获取小时
        var minute = ('0' + date.getMinutes()).slice(-2); // 获取分钟
        var second = ('0' + date.getSeconds()).slice(-2); // 获取秒
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    return "";
}


layui.use(['echarts'], function () {
    alert("111")
    var echarts = layui.echarts;
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(document.getElementById('sales - chart'));
    $.ajax({
        url: "/Purchase/SalesmanChart",
        type: "get",
        data: {
            token: localStorage.getItem("token")
        },
        success: function (res) {
            var obj = JSON.parse(res);
            console.log(obj);
            if (obj.code === 0) {
                // 正确构建数据
                var data = [];
                for (var i = 0; i < obj.data.xData.length; i++) {
                    data.push({
                        xData: obj.data.xData[i],
                        yData: obj.data.yData[i]
                    });
                }
                // 配置图表选项
                var option = {
                    title: {
                        text: '本季度 - 业务员销售排名'
                    },
                    xAxis: {
                        type: 'category',
                        data: data.map(function (item) { return item.xData; })
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            type: 'bar',
                            data: data.map(function (item) { return item.yData; })
                        }
                    ]
                };
                // 使用刚指定的配置项和数据显示图表。
                myChart.setOption(option);
            } else {
                console.log(res.msg);
            }
        },
        error: function () {
            console.log("获取数据失败");
        }
    });
});